<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="订单状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusList"
            :key="dict.status"
            :label="dict.value"
            :value="dict.status"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="applyPerson">
        <el-select
          v-model="queryParams.applyPerson"
          placeholder="选择申请人"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in kefuList"
            :key="dict.name"
            :label="dict.value"
            :value="dict.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请日期" prop="applyDate">
        <el-date-picker
          v-model="queryParams.applyDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="搜索" prop="keyword">
        <el-autocomplete
          style="width: 280px"
          class="inline-input"
          clearable
          v-model="queryParams.keyword"
          :fetch-suggestions="querySearch"
          placeholder="请输入订单号、手机号、班次搜索"
          @select="handleSelect"
          @keyup.enter.native="handleQuery"
        ></el-autocomplete>
        <!-- <el-input
          v-model="queryParams.keyword"
          placeholder="请输入订单号、手机号、班次搜索"
          clearable
          style="width: 280px"
          size="small"
          @keyup.enter.native="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['service:refOrderList:query']"
          >搜索</el-button
        >
        <el-button
          icon="el-icon-refresh"
          size="mini"
          v-hasPermi="['service:refOrderList:query']"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:post:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:post:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="分销商" align="center" prop="trader" />
      <el-table-column label="退款状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ newStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额（元）" align="center" prop="totalPay">
        <template slot-scope="scope">
          <span>{{ scope.row.totalPay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款金额（元）" align="center" prop="refundMoney">
        <template slot-scope="scope">
          <span>{{ scope.row.refundMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="退款原因"
        align="center"
        prop="refundReason"
        width="300"
      />
      <el-table-column label="申请人" align="center" prop="applyPerson" />
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ newDate(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="orderMessage(scope.row)"
            v-hasPermi="['service:refOrderList:edit']"
            >详情</el-button
          >
          <el-button
            v-show="scope.row.status === 0"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['service:refOrderList:edit']"
            >修改</el-button
          >
          <el-button
            v-show="scope.row.status === 0"
            size="mini"
            type="text"
            @click="cancleRef(scope.row)"
            v-hasPermi="['service:refOrderList:edit']"
            >取消申请</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="取消退款原因" :visible.sync="dialogVisible" width="30%">
      <span>退款原因：</span>
      <el-input
        style="margin-top: 10px"
        type="textarea"
        :rows="2"
        v-model="refModel.cancleReason"
        placeholder="请输入取消退款原因"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="refMessageFun">确 定</el-button>
      </span>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修退款对话框 -->
    <el-dialog
      title="修改退款申请"
      :visible.sync="open"
      width="550px"
      append-to-body
    >
      <order-ref v-on:success="success" :parentRefData="message"></order-ref>
    </el-dialog>
  </div>
</template>

<script>
import {
  querytrader,
  queryorderpwd,
  cleanprehistory,
  queryorderdetail,
  applyrefund,
  applyrefundfee,
} from "@/api/service/orderList";
import orderRef from "../module/orderListRef";
import {
  list,
  cancleapplyrefund,
  changerefund,
  queryreportpersonlist,
} from "@/api/service/refOrderList";
import utils from "../../js/index";

export default {
  name: "RefOrderList",
  components: {
    orderRef,
  },
  data() {
    return {
      kefuList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 状态列表
      statusList: [
        {
          status: 100,
          value: "全部",
        },
        {
          status: 0,
          value: "处理中",
        },
        {
          status: 1,
          value: "已退款",
        },
        {
          status: 2,
          value: "已撤销",
        },
        {
          status: 3,
          value: "第三方已处理",
        },
      ],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        applyPerson: localStorage.getItem("userName"),
        applyDate: undefined,
        status: 100,
        keyword: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" },
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" },
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        ],
      },
      // 取消退款模态框
      dialogVisible: false,
      // 取消退款参数
      refModel: {
        orderCode: undefined,
        cancleReason: undefined,
      },
      message: {},
      arr: [],
    };
  },
  created() {
    this.getList();
    this.getSearchList();
    this.getQueryreportpersonlist();
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    handleSelect(item) {
      console.log(item);
    },
    querySearch(queryString, cb) {
      try {
        var restaurants = this.arr;
        var results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      } catch (err) {}
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    getSearchList() {
      try {
        if (localStorage.getItem("searchList")) {
          this.arr = JSON.parse(localStorage.getItem("searchList"));
        }
      } catch (err) {}
      this.arr.unshift({
        value: this.queryParams.keyword,
        address: this.queryParams.keyword,
      });
      this.arr = utils.utils.arrUnique(this.arr);
      this.arr.splice(10, this.arr.length - 9);
      localStorage.setItem("searchList", JSON.stringify(this.arr));
    },
    getQueryreportpersonlist() {
      queryreportpersonlist().then((res) => {
        var list = res.data.map((e) => {
          return { name: e, value: e == "all" ? "全部" : e };
        });

        this.kefuList = list;
      });
    },
    cancleRef(code) {
      this.dialogVisible = true;
      this.refModel.orderCode = code.orderCode;
    },
    refMessageFun() {
      if (!this.refModel.cancleReason) {
        this.$message.error("请输入取消退款原因");
        return;
      }
      cancleapplyrefund(this.refModel).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.dialogVisible = false;
          this.refModel = {};
          this.$message.success(res.msg);
          this.getList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    orderMessage(order) {
      // 跳转到详情页面
      this.$router.push({
        path: `orderMessage`,
        query: {
          orderCode: order.orderCode,
        },
      });
    },
    newStatus(s) {
      switch (s) {
        case 0:
          return "处理中";
          break;
        case 1:
          return "已退款";
          break;
        case 2:
          return "已撤销";
          break;
        case 3:
          return "第三方已处理";
          break;
      }
    },
    newDate(date) {
      return utils.utils.NewDate(date);
    },
    getList() {
      this.loading = true;
      list(this.queryParams).then((response) => {
        this.postList = response.data.refundInfos;
        this.total = response.data.totalPage;
        this.loading = false;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 退款子组件模态框
    success(type, viewData) {
      viewData.refundFeeRate = viewData.refundFeeRate
        ? viewData.refundFeeRate
        : 0;
      const that = this;
      if (type == 1) {
        that.open = false;
      } else {
        changerefund(viewData)
          .then((res) => {
            if (res.code == 200) {
              that.open = false;
              that.getList();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            // this.$message.error(err);
          });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
      this.getSearchList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加岗位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: "正在获取数据...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const message = row.refundReason;
      queryorderdetail({ orderCode: row.orderCode })
        .then((res) => {
          if (res.code == 200) {
            loading.close();
            res.data.refMsg = row.refundReason;
            this.message = res.data;
            this.open = true;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.postId || this.ids;
      this.$confirm(
        '是否确认删除岗位编号为"' + postIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delPost(postIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>